package com.baize.filedowndemo.conversationFile

import android.util.Log
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.*

/**
 * requestBody   请求体
 * 文件上传进度回调
 */
class ProgressBody(var requestBody: RequestBody,var callBack:((Long,Long) -> Unit)? = null) : RequestBody() {

    private var mCurrentLength: Long = 0

    /**
     * 请求体的contentType
     */
    override fun contentType(): MediaType {
        return requestBody.contentType()!!
    }

    /**
     * 获取请求体总长度
     */
    override fun contentLength(): Long {
        return requestBody.contentLength()
    }

    /**
     * 文件写入
     */
    override fun writeTo(sink: BufferedSink) {
        try {
            //获取总长度
            val contentLength = contentLength()
            val forwardingSink = object : ForwardingSink(sink) {
                override fun write(source: Buffer, byteCount: Long) {
                    //增加当前写入的字节数
                    mCurrentLength += byteCount
                    callBack?.invoke(mCurrentLength, contentLength)
                    super.write(source, byteCount)
                }
            }
            val buffer = forwardingSink.buffer()
            requestBody.writeTo(buffer)
            // 刷新
            buffer.flush()
            buffer.close()
        } catch (e: Exception) {
            Log.i("baize", "writeTo: ${e.message}")
        }finally {
        }
    }

}